#include "qframedirstree.h"
#include "ui_qframedirstree.h"
#include <QFileDialog>
#include <QDebug>
#include <QDesktopServices>
QFrameDirsTree::QFrameDirsTree(QWidget *parent, QString name, QString type, QString path) :
    QWidget(parent),
    ui(new Ui::QFrameDirsTree)
{
    ui->setupUi(this);

    if(path == "")
    {
        //get settings
        QString setting_ini = QApplication::applicationDirPath() + "/user_data/setting.ini";
        settings = new QSettings(setting_ini,QSettings::IniFormat);
        QString dir_saved = settings->value(name,QApplication::applicationDirPath() +"/user_data/" + name).toString();
        ui->ui_lin_dir->setText(dir_saved);
    } else {
        //固定目录，不可修改类型
        ui->ui_lin_dir->setText(path);
        ui->ui_lin_dir->setVisible(false);
        ui->ui_btm_dir->setVisible(false); //固定目录不可选择
    }

    //tree trig
    ui->ui_tree_flow->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tocModelFlow = new QStandardItemModel(0, 1, this);

    file_filter = type;
    dir_save    = name;

    // --------------------------------------------
    // 初始化结束后需要加载的参数
    //默认打开路径
    update_files();

}

QFrameDirsTree::~QFrameDirsTree()
{
    delete ui;
}

void QFrameDirsTree::on_ui_btm_dir_clicked()
{
    QString p_dir  = QFileDialog::getExistingDirectory
                            (this,
                             "Please choose an work dir",
                             "");
    if (p_dir.isEmpty())
    {
        qDebug() << "你取消了选择。";
        return;
    }
    ui->ui_lin_dir->setText(p_dir);
    settings->setValue(dir_save,p_dir);

    update_files();
}
void QFrameDirsTree::update_files()
{

    // 初始化树状图
    tocModelFlow->clear();
    tocModelFlow->setHorizontalHeaderLabels({"文件导航"});
    ui->ui_tree_flow->setModel(tocModelFlow);
    //加载流程文档
    QStringList filters;
    QString team_name = file_filter; //设置文件类型
    filters << team_name;
    QDir dir(ui->ui_lin_dir->text());
    if (!dir.exists())
    {
        qDebug() << "目录不存在: " << dir;
        return;
    }
    dir.setNameFilters(filters);
    QStringList fileList = dir.entryList(QDir::Files);
    foreach(const QString &file , fileList)
    {
        QStandardItem * parentItem1 = new QStandardItem(file); //以第一个文件为父节点
        tocModelFlow->appendRow(parentItem1);
    }
}

void QFrameDirsTree::on_ui_tree_flow_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString s_node;
        s_node   = tocModelFlow->data(index,Qt::DisplayRole).toString();
        // 将文件路径转换为QUrl对象
        QString s_file = ui->ui_lin_dir->text() + "/" + s_node;
        QUrl fileUrl = QUrl::fromLocalFile(s_file);
        // 尝试打开文件
        if (QDesktopServices::openUrl(fileUrl)) {
            qDebug() << "文件已成功打开。";
            return;
        } else {
            qDebug() << "无法打开文件。" << s_node;
            //如果打不开目标日志文件
        }
    }
}



